//
//  ViewController.m
//  TestNetWork
//
//  Created by ren on 1/26/17.
//  Copyright © 2017 ren. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDelegate>

@property (nonatomic, strong) UITableView   *tableView;
@property (nonatomic, strong) UITextView    *textView;

@end

@implementation ViewController {
	UIActivityIndicatorView *indicator;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
	indicator = [UIActivityIndicatorView new];
    [self setButtons];
    [self setTextView];
	indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	indicator.center = CGPointMake(self.view.frame.size.width * 0.5, self.view.frame.size.height * 0.5);
	[self.view addSubview:indicator];
}

#pragma mark - add views
- (void)setButtons
{
	NSArray *arr = @[@(300101),@(300102),@(10255),@(10256),@(10257),@(10258),@(10880),@(10895),@(10301),@(10308),@(10317),@(10250),@(10432),@(10433),@(10423),@(10454),@(10252),@(10474),@(10475),@(300102),@(10262)];
    for (int i = 0; i < 20; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		NSInteger aInt = [arr[i] integerValue];
		[btn setTag:aInt];
        [btn setFrame:CGRectMake(0, 40 * i, 60, 40)];
        [btn setBackgroundColor:[UIColor redColor]];
        [btn setTitle:[NSString stringWithFormat:@"按钮%d",i] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
}

- (void)setTableView
{
    [self.tableView setFrame:CGRectMake(50, 0, [UIScreen mainScreen].bounds.size.width - 50, [UIScreen mainScreen].bounds.size.height)];
    [self.view addSubview:self.tableView];
}

- (void)setTextView
{
    [self.textView setFrame:CGRectMake(60, 0, [UIScreen mainScreen].bounds.size.width - 60, [UIScreen mainScreen].bounds.size.height)];
    [self.view addSubview:self.textView];
}

#pragma mark - lazy load
- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    }
    return _tableView;
}

- (UITextView *)textView
{
    if (_textView == nil) {
        _textView = [UITextView new];
    }
    return _textView;
}

#pragma mark button action
- (void)btnClick:(UIButton *)button
{
	NSString *catId = [NSString stringWithFormat:@"%ld", button.tag];
	[self requestData:catId];
}

#pragma mark network request
- (void)requestData:(NSString *)catId
{
	[indicator startAnimating];
    NSError *error;
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"https://preappapi.dmall.com:443/app/search/wareSearch"];//http://127.0.0.1:8000/passport/loginsearch/
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
//                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
//                                                       timeoutInterval:10.0];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
	request.timeoutInterval = 10;
	
    
//    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
	
    [request setValue:@"5AE222B7-4F09-4560-B43B-AE3DBC5C4E51" forHTTPHeaderField:@"idfa"];
    [request setValue:@"3.2.0" forHTTPHeaderField:@"apiVersion"];
    [request setValue:@"3.2.0" forHTTPHeaderField:@"version"];
    [request setValue:@"IOS" forHTTPHeaderField:@"platform"];
    [request setValue:@"APPSTORE" forHTTPHeaderField:@"channelId"];
    [request setValue:@"iPhone Simulator" forHTTPHeaderField:@"device"];
    [request setValue:@"10.2" forHTTPHeaderField:@"sysVersion"];
    [request setValue:@"com.dmall.dmallmainapp" forHTTPHeaderField:@"appName"];
    [request setValue:@"667*375" forHTTPHeaderField:@"screen"];
    [request setValue:@"5AE222B7-4F09-4560-B43B-AE3DBC5C4E51" forHTTPHeaderField:@"uuid"];
    [request setValue:@"ac" forHTTPHeaderField:@"xyz"];
    
    
    [request setValue:nil forHTTPHeaderField:@"token"];
    [request setValue:@"230" forHTTPHeaderField:@"storeId"];
    [request setValue:@"1" forHTTPHeaderField:@"venderId"];
    [request setValue:[NSString stringWithFormat:@"%d",1] forHTTPHeaderField:@"smartLoading"];//智能加载开关 0-关闭, 1-打开
    [request setValue:@"1" forHTTPHeaderField:@"networkType"];//网络类型：1-wifi, 2-2G, 3-3G/4G, 4-其它
    [request setValue:@"1486261648323" forHTTPHeaderField:@"currentTime"];
    
    [request setValue:@"37.785834" forHTTPHeaderField:@"lat"];
    [request setValue:@"-122.406417" forHTTPHeaderField:@"lng"];
    [request setValue:nil forHTTPHeaderField:@"gatewayCache"];
    [request setValue:@"1-230-1;2-230-1;" forHTTPHeaderField:@"storeGroup"];
    [request setValue:@"H4sIAAAAAAAAA02Pu26EMBBFfyWyUq4QYPAauhSpF4X0yIbxMgrYlh+Loij/HkOxpD1zH3N/SIw4kZbIsuKUAmMlcOAyl4JL3nDZQK0KJYqaKVCSUnIhr8YPD3AejU7GIs/KBMdZaA1LAm9d13/ePt4TDLiCD2K1pC0qzkpWsKqpaZ0y/OgA9DAD3udAWsauR3Dy461P1ujBDcdn5FRvOIWZtPSaEhZzR30qVjMd7djNRsNLj2tcRDBuv2kIm3FfQ/i2kCT5zoS1/0bQrMwOvKFC0iqxeLgQn/zwrBjPLqGjEmOIDtw+2NoFEn+Anp5P//4BP9QTQFoBAAA=" forHTTPHeaderField:@"bigdata"];
    
    
	NSString *categoryIDStr = catId;
	NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:categoryIDStr,@"categoryId",@(0),@"sortRule",@(0),@"sort",@(1),@"pageNum",@(1),@"businessCode",@(20),@"pageSize",@(1),@"from",@"230",@"erpStoreId",@"1",@"venderId",@(2),@"categoryLevel",@(0),@"sortKey",@(0),@"thirdCategoryId",@(1),@"categoryType",@(false),@"globalSelection",nil];
	
	NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mapData options:NSJSONWritingPrettyPrinted error:nil];
	NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"\n " withString:@""];
	NSString *json = [@"param=" stringByAppendingString:jsonString];
//	NSDictionary *param = @{@"param":jsonString};
	
//	NSString *json = @"param={\"phone\":\"18510087800\",\"setPwd\":0,\"pwd\":\"2f6abf78318cff992108d3aff683a0b7\",\"cid\":\"ad774de343a87952a687880c7efdbf01\"}";
//	NSDictionary *param = @{@"param":json};
	
//    NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
    [request setHTTPBody:[json dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",dic.description);
                [self.textView setText:[NSString stringWithFormat:@"%@",[self responseJson:dic]]];
                [self.textView setTextColor:[UIColor blackColor]];
				[indicator stopAnimating];
            });
        }
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
				NSLog(@"%@",error.userInfo.description);
                [self.textView setText:[NSString stringWithFormat:@"%@",error.userInfo.description]];
                [self.textView setTextColor:[UIColor redColor]];
				[indicator stopAnimating];
            });
        }
    }];
    [postDataTask resume];
    
//    NSURL *URL = [NSURL URLWithString:@"http://127.0.0.1:8000/?a=1"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
//
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
//                                            completionHandler:
//                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
//                                      NSLog(@"123");
//                                  }];
//    
//    [task resume];
}

- (id)responseJson:(id)response
{
	if ([NSJSONSerialization isValidJSONObject:response]) {
		NSData *jsonData = [NSJSONSerialization dataWithJSONObject:response options:NSJSONWritingPrettyPrinted error:nil];
		NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
		response = jsonString;
	}
	return response;
}


//- (void)URLSession:(NSURLSession *)session
//didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
// completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
//{
//	//AFNetworking中的处理方式
//	NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//	__block NSURLCredential *credential = nil;
//	//判断服务器返回的证书是否是服务器信任的
//	if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//		credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//		/*disposition：如何处理证书
//		 NSURLSessionAuthChallengePerformDefaultHandling:默认方式处理
//		 NSURLSessionAuthChallengeUseCredential：使用指定的证书    NSURLSessionAuthChallengeCancelAuthenticationChallenge：取消请求
//		 */
//		if (credential) {
//			disposition = NSURLSessionAuthChallengeUseCredential;
//		} else {
//			disposition = NSURLSessionAuthChallengePerformDefaultHandling;
//		}
//	} else {
//		disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
//	}
//	//安装证书
//	if (completionHandler) {
//		completionHandler(disposition, credential);
//	}
//}
//// 接收到服务器的响应
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
//{
//	NSLog(@"didReceiveResponse");
//	completionHandler(NSURLSessionResponseAllow);
//}
//// 接收到服务器返回的数据
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
//{
//	NSLog(@"didReceiveData");
//}
//// 请求完毕
//- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
//{
//	NSLog(@"didCompleteWithError");
//}

#pragma mark - tableview datasource
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
